import re
import util

def smita(reader):
    data = {}
    headers = reader.next()
    for row in reader:
        for entry, header in zip(row, headers):
            if entry == '':
                continue
            m = re.match(r'[0-9]+: Sample_([^ ]+) ([^0-9]+)([0-9]+)\.fcs', entry)
            if m:
                celltype = header
                stimulus, state, run = m.groups()
                state = state.capitalize()
                run = int(run)
            else:
                pstat = header
                mfi = float(entry)
                if state not in data:
                    data[state] = {}
                node = celltype + ', ' + stimulus + ', ' + pstat
                if node not in data[state]:
                    data[state][node] = []
                data[state][node].append(mfi)
    return data

def smita2(reader):
    data = {}
    headers = reader.next()
    for row in reader:
        celltype, stim, state = row[:3]
        for entry, header in zip(row[3:], headers[3:]):
            if entry == '':
                continue
            pstat = header
            node = celltype + ', ' + stim + ', ' + pstat
            mfi = float(entry)
            if state not in data:
                data[state] = {}
            if node not in data[state]:
                data[state][node] = []
            data[state][node].append(mfi)
    return data

def jason(reader):
    data = {}
    headers = reader.next()[1:]
    for row in reader:
        state, = re.match(r'^([^0-9]+)[0-9]+$', row[0]).groups()
        for entry, header in zip(row[1:], headers):
            try:
                mfi = float(entry)
            except ValueError:
                mfi = None
            if state not in data:
                data[state] = {}
            node = header
            if node not in data[state]:
                data[state][node] = []
            data[state][node].append(mfi)
    for state in data:
        for node in data[state]:
            old = data[state][node]
            av = util.avg([x for x in old if x is not None])
            data[state][node] = [x or av for x in old]
    return data
